<?php

namespace App\Logic\Member\Form;

use App\Core\BaseListForm;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Model\Member\MemberProfitStatisticsModel;
use App\Model\Member\MemberScoreModel;
use App\Model\Order\OrderModel;
use App\Util\UserIdentityHelper;

class MemberListForm extends BaseListForm{
    /**
     * *
     * `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
     * `salt` char(9) NOT NULL DEFAULT '' COMMENT '密码种子',
     * `password` varchar(128) NOT NULL DEFAULT '' COMMENT '密码md5（输入的值+salt）',
     * `username` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名',
     * `name` varchar(128) NOT NULL DEFAULT '' COMMENT '姓名',
     * `phone` varchar(12) NOT NULL DEFAULT '' COMMENT '手机号',
     * `referrer_id` int(11) NOT NULL DEFAULT '0' COMMENT '推荐人',
     * `usdt` varchar(255) NOT NULL DEFAULT '' COMMENT 'usdt地址',
     * `alipay_qr` varchar(255) NOT NULL DEFAULT '' COMMENT '支付宝收款码',
     * `wepay_qr` varchar(255) NOT NULL DEFAULT '' COMMENT '微信收款码',
     * `pub_bank_name` varchar(255) NOT NULL DEFAULT '' COMMENT '对公收款银行',
     * `pub_bank_deposit` varchar(255) NOT NULL DEFAULT '' COMMENT '对公开户银行',
     * `pub_bank_account_name` varchar(255) NOT NULL DEFAULT '' COMMENT '对公开户姓名',
     * `pub_bank_account_no` varchar(255) NOT NULL DEFAULT '' COMMENT '对公银行帐号',
     * `pri_bank_name` varchar(255) NOT NULL DEFAULT '' COMMENT '对私收款银行',
     * `pri_bank_deposit` varchar(255) NOT NULL DEFAULT '' COMMENT '对私开户银行',
     * `pri_bank_account_name` varchar(255) NOT NULL DEFAULT '' COMMENT '对私开户姓名',
     * `pri_bank_account_no` varchar(255) NOT NULL DEFAULT '' COMMENT '对私银行帐号',
     * `score` decimal(10,2) NOT NULL COMMENT '积分代币',
     * `profit` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '单利润',
     * `state` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '账号状态[0:停用 1:启用]',
     * `remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注/员工介绍',
     *
     *  */
    public $id;
    public $state;//用户状态
    public $type;//用户等级
    public $username;//用户名
    public $name;//姓名
    public $phone;
    public $referrer_id;//推荐人
    public $usdt;//usdt地址
    public $alipay_qr;//支付宝收款码
    public $wepay_qr;//微信收款码
    public $pub_bank_name;//对公收款银行
    public $pub_bank_deposit;//对公开户银行
    public $pub_bank_account_name;//对公开户姓名
    public $pub_bank_account_no;//对公银行账号
    public $pri_bank_name;//对私收款银行
    public $pri_bank_deposit;//对私开户银行
    public $pri_bank_account_name;//对私开户姓名
    public $pri_bank_account_no;//对私银行账号
    public $score;//积分代币
    public $profit;//每单提成
    public $start_created_at;//注册时间 - 开始
    public $end_created_at;//注册时间 - 结束
    public $start_last_login_time;//最后登录时间 - 开始
    public $end_last_login_time;//最后登录时间 - 结束

    public function lists()
    {
        $where = [];
        /**
    检索
         */
        if ($this->checkField($this->id)) {
            $where['id'] = $this->id;
        }
        if ($this->checkField($this->username)) {
            $where['username'] = $this->username;
        }
        if ($this->checkField($this->name)) {
            $where['name'] = $this->name;
        }
        if ($this->checkField($this->phone)) {
            $where['phone'] = $this->phone;
        }
        if ($this->checkField($this->referrer_id)) {
            $where['referrer_id'] = $this->referrer_id;
        }

        /**
        用户状态检索
         */
        if ($this->checkField($this->state)) {
            $where['state'] = $this->state;
        }

        /**
        注册时间检索
         */
        if ($this->checkField($this->start_created_at) && $this->checkField($this->end_created_at)) {
            $where['created_at'] = [[$this->start_created_at, $this->end_created_at], 'between'];
        }elseif ($this->checkField($this->start_created_at)) {
            $where['created_at'] = [$this->start_created_at, '>='];
        }elseif ($this->checkField($this->end_created_at)) {
            $where['created_at'] = [$this->end_created_at, '<='];
        }
        /**
        最后登录时间检索
         */
        if ($this->checkField($this->start_last_login_time) && $this->checkField($this->end_last_login_time)) {
            $where['last_login_time'] = [[$this->start_last_login_time, $this->end_last_login_time], 'between'];
        }elseif ($this->checkField($this->start_last_login_time)) {
            $where['last_login_time'] = [$this->start_last_login_time, '>='];
        }elseif ($this->checkField($this->end_last_login_time)) {
            $where['last_login_time'] = [$this->end_last_login_time, '<='];
        }



        $model       = MemberModel::makeQueryModel($where, [], $this->getPagination())
            ->order('id', 'DESC');
        $modelResult = $model->all();


        $list = [];
        foreach ($modelResult as $v) {
//            $item = $v->toArray();
            $item   = [
                'id'                    => $v->id,
                'username'              => $v->username,
                'name'                  => $v->name,
                'referrer_id'           => $v->referrer_id,
                'usdt'                  => $v->usdt,
                'alipay_qr'             => $v->alipay_qr,
                'wepay_qr'              => $v->wepay_qr,
                'pub_bank_name'         => $v->pub_bank_name,
                'pub_bank_deposit'      => $v->pub_bank_deposit,
                'pub_bank_account_name' => $v->pub_bank_account_name,
                'pub_bank_account_no'   => $v->pub_bank_account_no,
                'pri_bank_name'         => $v->pri_bank_name,
                'pri_bank_deposit'      => $v->pri_bank_deposit,
                'pri_bank_account_name' => $v->pri_bank_account_name,
                'pri_bank_account_no'   => $v->pri_bank_account_no,
                'score'                 => $v->score,
                'profit'                => $v->profit,
                'profit_score'          => $v->profit_score,
                'subordinate_count'     => $v->subordinate_count,
                'subordinate_score'     => $v->subordinate_score,
                'locked_day'            => $v->locked_day,
                'state'                 => $v->state,
                'state_label'           => MemberModel::getStateDict($v->type),
                'remark'                => $v->remark,
                'created_at'            => $v->created_at,
                'last_count_time'       => $v->last_count_time
            ];
            $list[] = $item;
        }

        /**如果是推荐列表,那么就要统计推荐收益*/
        if ($this->checkField($this->referrer_id) && !empty($list)) {
            /**总提成*/
            $list = $this->calculateTeamProfit($list, 'all');
            /**当日提成*/
            $list = $this->calculateTeamProfit($list, 'day');
            /**本周提成*/
            $list = $this->calculateTeamProfit($list, 'week');
            /**本月提成*/
            $list = $this->calculateTeamProfit($list, 'month');
            /**本年提成*/
            $list = $this->calculateTeamProfit($list, 'year');
        }

        $total = $model->lastQueryResult()->getTotalCount();

        $pagination                = $this->getPagination();
        $pagination['total_count'] = $total;

        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];

        return $result;
    }

    /**计算团队提成*/
    private function calculateTeamProfit($list, $type)
    {
        $ids = array_column($list, 'id');
        /**
         * SELECT source_id, SUM(score) FROM ss_member_profit_statistics WHERE user_id=4611712 AND type='REFFERERPROFIT' AND source_id IN (4611713, 4611714)
         * GROUP BY source_id
         */
        $where = [
            'user_id'  => $this->referrer_id,
            'type'     => MemberProfitScoreModel::TYPE_REFFERER_PROFIT,
            'source_id' => [$ids, 'IN']
        ];
        $field = 'referrer_profit';
        switch ($type){
            case 'day':
                $where['date'] = date('Y-m-d');
                $field = 'referrer_profit_day';
                break;
            case 'week':
                /**取出本周的开始和结束日期*/
                $week_start_date = date('Y-m-d 00:00:00', strtotime('last monday'));
                $week_end_date = date('Y-m-d 23:59:59', strtotime('next sunday'));
                $where['date'] = [[$week_start_date, $week_end_date], 'between'];
                $field = 'referrer_profit_week';
                break;
            case 'month':
                /**取出本月的开始和结束日期*/
                $month_start_date = date('Y-m-01 00:00:00');
                $month_end_date = date('Y-m-d 23:59:59', strtotime(date('Y-m-01', strtotime('+1 month')))-1);
                $where['date'] = [[$month_start_date, $month_end_date], 'between'];
                $field = 'referrer_profit_month';
                break;
            case 'year':
                /**取出本年的开始和结束日期*/
                $year_start_date = date('Y-01-01 00:00:00');
                $year_end_date = date('Y-12-31 23:59:59');
                $where['date'] = [[$year_start_date, $year_end_date], 'between'];
                $field = 'referrer_profit_year';
                break;
            case 'all':
            default:
                break;
        }
        $referrer = MemberProfitStatisticsModel::makeQueryModel($where)
            ->field(['source_id', 'SUM(amount) as total_score'])
            ->group('source_id')
            ->all();
        if($referrer){
            foreach ($referrer as $v){
                foreach ($list as &$item){
                    if($item['id'] == $v->source_id){
                        $item[$field] = $v->total_score;
                        break;
                    }
                }
            }
        }
        return $list;
    }

}
